package com.jt.provider.callback;



import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
@Component
@Slf4j
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        //设置响应数据的编码
        httpServletResponse.setCharacterEncoding("utf-8");
        //告诉浏览器响应的类型以及编码(浏览器呈现的编码)
        httpServletResponse.setContentType("text/html;charset=utf-8");
        //响应的状态吗
        httpServletResponse.setStatus(429);

        PrintWriter out = httpServletResponse.getWriter();
        if(e instanceof FlowException){
            System.out.println("<h2>访问太频繁</h2>");
            out.print("<h2>访问太频繁</h2>");
        }else if(e instanceof DegradeException){
            System.out.println("<h2>服务维护中，稍等片刻</h2>");
            out.print("<h2>服务维护中，稍等片刻</h2>");
        }
        out.flush();
        out.close();
    }
}
